package com.advertisementsystem.Controller;

import com.advertisementsystem.Dto.PaymentDTO;
import com.advertisementsystem.Exception.BusinessException;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.Servie.PaymentService;
import com.advertisementsystem.utils.PayUtils;
import com.advertisementsystem.vo.PaymentVO;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    /**
     * 创建支付订单
     */
    @PostMapping
    @PreAuthorize("hasRole('ADVERTISER')")
    public ResponseResult<PaymentVO> createPayment(@RequestBody @Valid PaymentDTO dto) {
        return ResponseResult.success(paymentService.createPayment(dto));
    }

    /**
     * 支付回调接口
     */
    @PostMapping("/callback/{payMethod}")
    public String handlePaymentCallback(
            @PathVariable String payMethod,
            HttpServletRequest request) {
        try {
            // 验证签名
            if (!PayUtils.verifySign(payMethod, request)) {
                return "sign_verify_failed";
            }

            // 解析回调参数
            String orderNo = PayUtils.getOrderNo(payMethod, request);
            String transactionId = PayUtils.getTransactionId(payMethod, request);
            Integer status = PayUtils.getPayStatus(payMethod, request);

            // 处理支付结果
            paymentService.handlePaymentCallback(orderNo, transactionId, status);

            return "success";
        } catch (Exception e) {
            log.error("Handle payment callback error", e);
            return "fail";
        }
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/status/{orderNo}")
    @PreAuthorize("hasRole('ADVERTISER')")
    public ResponseResult<PaymentVO> getPaymentStatus(@PathVariable String orderNo) {
        return ResponseResult.success(paymentService.getPaymentStatus(orderNo));
    }

    /**
     * 获取支付历史
     */
    @GetMapping("/history")
    @PreAuthorize("hasRole('ADVERTISER')")
    public ResponseResult<IPage<PaymentVO>> getPaymentHistory(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return ResponseResult.success(
                paymentService.getPaymentHistory(pageNum, pageSize));
    }
}
